using System;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using THANHTUNGO.Portal.Admin;
using THANHTUNGO.Portal.Components;
using THANHTUNGO.Portal.Components.Security;
using THANHTUNGO.Portal.Components.Settings;
using THANHTUNGO.Portal.Security;

namespace THANHTUNGO.Portal
{
    public class ManageUsers : Page
    {
        protected TextBox Email;
        protected TextBox Password;
        protected DropDownList allRoles;
        protected LinkButton addExisting;
        protected DataList userRoles;
        protected LinkButton saveBtn;
        protected HtmlGenericControl title;
        protected LinkButton UpdateUserBtn;

        private int userId = -1;
        private string userName = "";
        private int tabIndex = 0;
        protected TextBox ConfirmPassword;
        protected RequiredFieldValidator RequiredFieldValidator1;
        protected CompareValidator CompareValidator1;
        protected RequiredFieldValidator RequiredFieldValidator2;
        private int tabId = 0;

        //*******************************************************
        //
        // The Page_Load server event handler on this page is used
        // to populate the role information for the page
        //
        //*******************************************************

        private void Page_Load(object sender, EventArgs e)
        {
            // Calculate userid
            if (Request.Params["userid"] != null)
            {
                userId = Int32.Parse(Request.Params["userid"]);
            }
            if (Request.Params["username"] != null)
            {
                userName = (string) Request.Params["username"];
            }
            if (Request.Params["tabid"] != null)
            {
                tabId = Int32.Parse(Request.Params["tabid"]);
            }
            if (Request.Params["tabindex"] != null)
            {
                tabIndex = Int32.Parse(Request.Params["tabindex"]);
            }


            // If this is the first visit to the page, bind the role data to the datalist
            if (Page.IsPostBack == false)
            {
                // new user?
                if (userName == "")
                {
                    User users = new User();

                    // make a unique new user record
                    int uid = -1;
                    int i = 0;

                    while (uid == -1)
                    {
                        string friendlyName = "New User created " + DateTime.Now.ToString();
                        userName = "New User" + i.ToString();
                        users.Name = friendlyName;
                        users.Email = userName;
                        uid = users.Insert();
                        i++;
                    }

                    // redirect to this page with the corrected querystring args
                    Response.Redirect("~/Admin/ManageUsers.aspx?userId=" + uid + "&username=" + userName + "&tabindex=" + tabIndex + "&tabid=" + tabId);
                }

                BindData();
            }
        }

        //*******************************************************
        //
        // The Save_Click server event handler on this page is used
        // to save the current security settings to the configuration system
        //
        //*******************************************************

        private void Save_Click(Object Sender, EventArgs e)
        {
            // Obtain PortalSettings from Current Context
            PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

            // Navigate back to admin page
            Response.Redirect("~/Default.aspx?tabindex=" + tabIndex + "&tabid=" + tabId);
        }

        //*******************************************************
        //
        // The AddRole_Click server event handler is used to add
        // the user to this security role
        //
        //*******************************************************

        private void AddRole_Click(Object sender, EventArgs e)
        {
            int roleId;

            //get user id from dropdownlist of existing users
            roleId = Int32.Parse(allRoles.SelectedItem.Value);

            // Add a new userRole to the database
            Role roles = new Role();
            roles.AssignRoleToUser(roleId, userId);

            // Rebind list
            BindData();
        }

        //*******************************************************
        //
        // The UpdateUser_Click server event handler is used to add
        // the update the user settings
        //
        //*******************************************************

        private void UpdateUser_Click(Object sender, EventArgs e)
        {
            // update the user record in the database
            User user = new User();
            user.ID = userId;
            user.Email = Email.Text;
            user.Password = PortalSecurity.Encrypt(Password.Text);
            user.Update();

            // redirect to this page with the corrected querystring args
            Response.Redirect("~/Admin/ManageUsers.aspx?userId=" + userId + "&username=" + Email.Text + "&tabindex=" + tabIndex + "&tabid=" + tabId);
        }

        //*******************************************************
        //
        // The UserRoles_ItemCommand server event handler on this page
        // is used to handle deleting the user from roles
        // from the userRoles asp:datalist control
        //
        //*******************************************************

        private void UserRoles_ItemCommand(object sender, DataListCommandEventArgs e)
        {
            Role roles = new Role();
            int roleId = (int) userRoles.DataKeys[e.Item.ItemIndex];

            // update database
            roles.DeleteUserRole(roleId, userId);

            // Ensure that item is not editable
            userRoles.EditItemIndex = -1;

            // Repopulate list
            BindData();
        }

        //*******************************************************
        //
        // The BindData helper method is used to bind the list of
        // security roles for this portal to an asp:datalist server control
        //
        //*******************************************************

        private void BindData()
        {
            // Bind the Email and Password
            User user = new User();
            if (user.Load(userName))
            {
                Email.Text = user.Email;
            }

            // add the user name to the title
            if (userName != "")
            {
                title.InnerText = "Manage User: " + userName;
            }

            // bind users in role to DataList
            userRoles.DataSource = Components.Security.User.GetRolesByEmail(userName);
            userRoles.DataBind();

            // Obtain PortalSettings from Current Context
            PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

            // bind all portal roles to dropdownlist
            allRoles.DataSource = Role.SelectAll();
            allRoles.DataBind();
        }

        public ManageUsers()
        {
            Page.Init += new EventHandler(Page_Init);
        }

        private void Page_Init(object sender, EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
        }

        #region Web Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.UpdateUserBtn.Click += new System.EventHandler(this.UpdateUser_Click);
            this.addExisting.Click += new System.EventHandler(this.AddRole_Click);
            this.userRoles.ItemCommand += new System.Web.UI.WebControls.DataListCommandEventHandler(this.UserRoles_ItemCommand);
            this.saveBtn.Click += new System.EventHandler(this.Save_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion
    }
}